package org.moon.framework.autoconfigure.sms.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.google.common.collect.Lists;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.moon.framework.autoconfigure.exception.domain.MoonException;
import org.moon.framework.autoconfigure.sms.SmsService;
import org.moon.framework.autoconfigure.sms.domain.SmsResponse;
import org.moon.framework.autoconfigure.sms.props.SmsProperties;
import org.moon.framework.autoconfigure.utils.Func;
import org.moon.framework.autoconfigure.utils.JsonUtils;
import org.springframework.http.HttpStatus;

import java.util.List;
import java.util.Map;

/**
 * 阿里云短信
 * @author ninglong
 */
@Slf4j
public class AliSmsProviderImpl implements SmsService,SmsProvider {

    private Client acsClient = null;
    private SmsProperties smsProperties = null;

    @Override
    public SmsService builder(SmsProperties smsProperties){
        this.smsProperties = smsProperties;
        Config config = new Config()
                .setAccessKeyId(smsProperties.getAccessKey())
                .setAccessKeySecret(smsProperties.getSecretKey())
                .setEndpoint(smsProperties.getDomain()).setRegionId(smsProperties.getRegionId());
        try {
            acsClient = new Client(config);
        }catch (Exception e){
            throw new MoonException("阿里云短信客户端初始化失败");
        }
        return this;
    }

    @Override
    public SmsResponse sendSingleSms(String mobile, String templateCode, Map<String, String> templateParams) {
        List<String> mobiles = Lists.newArrayList();
        mobiles.add(mobile);
        return sendMultiSms( mobiles, templateCode, templateParams);
    }

    @Override
    public SmsResponse sendMultiSms(List<String> mobiles, String templateCode, Map<String, String> templateParams) {
        SendSmsRequest sendSmsRequest = (new SendSmsRequest()).setPhoneNumbers(String.join(Func.COMMA, mobiles))
                .setTemplateCode(templateCode).setTemplateParam(JsonUtils.obj2string(templateParams)).setSignName(this.smsProperties.getSignName());
        try {
            SendSmsResponse sendSmsResponse = this.acsClient.sendSms(sendSmsRequest);
            SendSmsResponseBody body = sendSmsResponse.getBody();
            return new SmsResponse("OK".equalsIgnoreCase(body.getCode()), "OK".equalsIgnoreCase(body.getCode()) ? 200 : 500, body.getMessage());
        } catch (Exception var6) {
            var6.printStackTrace();
            return new SmsResponse(Boolean.FALSE, HttpStatus.INTERNAL_SERVER_ERROR.value(), var6.getMessage());
        }
    }
}
